import { loginAuth, getInfo, logout } from '@/api/login'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'
import globalSetting from '@/config.js'
import md5 from "js-md5"
import axios from 'axios'

const state = {
  token: getToken(),
  userInfo: getUserInfo(),
  id: '',
  account: '',
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  }
}

const actions = {
	// 用户登录
	login({ commit }, userInfo) {
		const { account, password } = userInfo;
		return new Promise((resolve, reject) => {
			// 有空重新整理
			let params = {
				client_id: "admin",
				client_secret: "123456",
				scope: "all",
				grant_type: "account",
				account: account.trim(),
				password: md5(password),
				timestamp: '',
				code: '',
				origin: "password",
			}
			const paramsNew = new URLSearchParams(params);
			const queryString = paramsNew.toString();
			
			axios.post(globalSetting.domain+'/api/oauth/Login', queryString, {
			  headers: {
			    'Content-Type': 'application/x-www-form-urlencoded'
			  }
			}).then(response => {
				const { data } = response;
				
				console.log(data,'---data---1111');
				
				if(data.code == 200) {
					let token = data.data.token;
					commit('SET_TOKEN', token);
					setToken(token);
					resolve();
				}else {
					reject(data.msg);
				}
			}).catch(error => {
				reject(error);
			});
		})
	},

	// 重置页面状态
	resetState({ commit }, state) {
		let pageState = getState();
		pageState[state.key] = state.value
		setState(pageState);
	},
	
	// 获取用户信息
	getInfo({ commit, state }) {
		return new Promise((resolve, reject) => {
			getInfo(state.token).then(response => {
				const { data } = response
				if (!data) {
				  reject('验证失败，请重新登录！')
				}
				const { id, account } = data
				// commit('SET_ACCOUNT', account)
				resolve(data)
			}).catch(error => {
				reject(error)
			})
		})
	},

	// 用户退出登录
	logout({ commit, state, dispatch }) {
		return new Promise((resolve, reject) => {
			logout().then(response => {
				commit('SET_TOKEN', '')
				removeToken();
				removeUserInfo();
				resolve();
			}).catch(error => {
				reject(error)
			})
			
		})
	},

	// remove token
	resetToken({ commit }) {
		return new Promise(resolve => {
		  commit('SET_TOKEN', '')
		  removeToken()
		  removeUserInfo()
		  resolve()
		})
	}

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
